package com.easylinkin.linkappapi.elasticsearch.entity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.easylinkin.linkappapi.elasticsearch.util.EsCalendar;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * <p>
 * 告警通知日志
 * </p>
 *
 * @author TongJie
 * @since 2020-05-14
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("linkapp_alarm_banknotice_log")
public class BankAlarmNotice extends Model<BankAlarmNotice> {

    private static final long serialVersionUID = 1L;
    
    private static final Integer WEEKALARMTYPE   = 1;
  
    
    /**
     * 主键
     */
    @TableId("id")
    private String id;

    /**
     * 告警类型 1周 2 月
     */
    @TableField("alarm_type")
    private Integer alarmType;

    /**
     * 数据源id
     */
    @TableField("data_source_id")
    private String dataSourceId;
    

   
    /**
     * 告警内容
     */
    @TableField("content")
    private String content;

  
    /**
     * 当期统计结果
     */
    @TableField("current_statistic")
    private Double currentStatistic;
    
    /**
     * 环比统计结果
     */
    @TableField("mom_statistic")
    private Double momStatistic;
    
    /**
     * 环比率
     */
    @TableField("mom_rate")
    private Float momRate;

    /**
     * 发送状态；0发送失败，1发送成功
     */
    @TableField("status")
    private Integer status = 0;

    /**
     * 发送时间
     */
    @TableField("alarm_date")
    private Date alarmDate;
 
    /**
     * 告警方式
     */
    @TableField("alarm_way")
    private String  alarmWay;
    
    
    /**
     * 数据源名称
     */
    @TableField(exist = false)
    private String dataSourceName;
  
    /**
     * 上期的时间段
     */
    @TableField(exist = false)
	private String  momPeriod;
    /**
     * 当期的时间段
     */
    @TableField(exist = false)
	private String  currentPeriod;
    
    
	//当期的起始时间
    @TableField(exist = false)
	private Date currentBeginTime;
	//当期的结束时间
    @TableField(exist = false)
	private Date currentEndTime;
    //环比时间起始时间
    @TableField(exist = false)
	private Date momBeginTime;
	//环比时间结束时间
    @TableField(exist = false)
	private Date momEndTime;
    /**
     * 告警模板id
     */
    @TableField(exist = false)
    private String templetId;

    /**
     * 告警阀值
     */
    @TableField(exist = false)
    private Float alarmThr;
    /**
     * 告警模板（短信）
     */
    @TableField(exist = false)
    private String templetMessageContent;


    /**
     * 告警模板（邮箱）
     */
    @TableField(exist = false)
    private String templeteMailContent;

    /**
     * 告警方式(电话号码)
     */
    @TableField(exist = false)
    private String phoneNumber;


    /**
     * 邮箱地址(电话号码)
     */
    @TableField(exist = false)
    private String emailAddress;
    
    /**
     * 是否告警通知 0否 1是
     */
    @TableField(exist = false)
    private Integer isNotice;
    
    
    /**
     * 能源类型
     */
    @TableField(exist = false)
    private String energyKind;
    
    
    
    public  void setCurrentPeriodAndMomPeriod(MomStatisticModel model){
	     String  currentBeginTime = EsCalendar.getyyyyMMddFromromDate(model.getCurrentBeginTime());
	     String  currentEndTime = EsCalendar.getyyyyMMddFromromDate(model.getCurrentEndTime());
	     String  momBeginTime 	= EsCalendar.getyyyyMMddFromromDate(model.getMomBeginTime());
	     String  momEndTime  =  EsCalendar.getyyyyMMddFromromDate(model.getMomEndTime());
	     StringBuffer currentBuffer = new StringBuffer("(");
	     currentBuffer.append(currentBeginTime).append("-").append(currentEndTime).append(")");
	     StringBuffer momBuffer = new StringBuffer("(");
	     momBuffer.append(momBeginTime).append("-").append(momEndTime).append(")");
	     currentPeriod = currentBuffer.toString();
	     momPeriod = momBuffer.toString();
   
    }
    
    
    /**
     * 从告警规则的参数中解析出告警实例
     * @throws ParseException 
     */
    public   void  initialBankAlarmNoticeFrmParmJson(String  paramString) throws ParseException {
    	JSONObject  jsonObject = (JSONObject) JSON.parse(paramString);
    	
    	Date date  = new Date ();
        Date currentBeginTime;
        Date currentEndTime;
    
    	this.setDataSourceId(jsonObject.getString("dataSourceId")); 
    	this.setIsNotice(jsonObject.getInteger("isNotice"));
    	this.setEnergyKind(jsonObject.getString("energyKind"));
    	this.setPhoneNumber(jsonObject.getString("phone"));
    	this.setEmailAddress(jsonObject.getString("email"));
    	this.setAlarmThr(jsonObject.getFloat("alarmThr"));
    	Integer alarmType = jsonObject.getInteger("alarmType");
    	this.setAlarmType(alarmType);
    	//起始时间，终止时间
    	if(alarmType!=null&&alarmType==1)//周告警
    	{
    	currentBeginTime = EsCalendar.getDateByWeekCountAndWeekNumber(-1, Calendar.MONDAY);
    	currentEndTime   = EsCalendar.getDateByWeekCountAndWeekNumber(-1, Calendar.SUNDAY);
    	}
    	else//月告警
    	{
		currentBeginTime = EsCalendar.getBefreMonthfirstDayByDate(date, 1);
		currentEndTime = EsCalendar.getBefreMonthLastDayByDate(date, 1);
    	}
    	this.setCurrentBeginTime(currentBeginTime);
    	this.setCurrentEndTime(currentEndTime);
    	this.setAlarmDate(date);
     }
     
    
    
  
   
   public  static String getBankParmJsonString(BankAlarmNotice bankAlarmNotice) {
        JSONObject param = new JSONObject();
        param.put("dataSourceName", bankAlarmNotice.getDataSourceName());
        
        String alarmType;
        if(bankAlarmNotice.getAlarmType()==1){
        	alarmType ="周";
        }else{
        	alarmType ="月";
        }
        param.put("alarmType", alarmType);
        param.put("beforeDate",bankAlarmNotice.getMomPeriod());
        param.put("beforeCount",bankAlarmNotice.getMomStatistic());
        param.put("currentDate",bankAlarmNotice.getCurrentPeriod());
        param.put("currenCount",bankAlarmNotice.getCurrentStatistic());
        param.put("momRate",bankAlarmNotice.getMomRate());
        return param.toString();
    }
   
   /**
    * 贷后管理告警内容
    * 
    */
   public    String getBankAlarmContent() {
    	 String alarmType;
          if(this.alarmType==1){
          	alarmType ="周";
          }else{
          	alarmType ="月";
          }
    	 StringBuffer  buffer  =  new StringBuffer("尊敬的管理用户:你负责的");   
         buffer
    	.append(dataSourceName).append("发生了").append(alarmType).append("环比用电异常，").append("上上期")
    	.append(momPeriod).append("用电数据").append(momStatistic)
    	.append(",").append("上期").append(currentPeriod).append("用电数据").append(currentStatistic).append("环比值为").append(momRate)
    	.append("%。").append(" 请核实用电情况，注意金融风险.");
        return buffer.toString();
    }
   
   
   
     public  String getBankEmaiBodyText(Template  template) throws IOException, TemplateException {
         Map<String, String> param = new HashMap<String, String>();
         String  alarmType; 
 	     String  momRate;
         Double  momStatistic     = this.getMomStatistic();
         Double  currentStatistic  = this.getCurrentStatistic();
  	     NumberFormat     format   = NumberFormat.getInstance();
  	     format.setMaximumFractionDigits(4);
  	     momRate = format.format((momStatistic-currentStatistic)*100/momStatistic);
	     if(WEEKALARMTYPE.equals(this.getAlarmType()) ){
	    	alarmType ="周";
	     }else{
	     	alarmType ="月";
	     }
	       param.put("dataSourceName",this.getDataSourceName());
	       param.put("alarmType",   alarmType);
	       param.put("beforeDate",  this.getMomPeriod());
	       param.put("beforeCount", this.getMomStatistic().toString());
	       param.put("currentDate", this.getCurrentPeriod());
	       param.put("currenCount", this.getCurrentStatistic().toString());
	       param.put("momRate", momRate);
       
		   StringWriter writer = new StringWriter();
		   template.process(param, writer);
		   
		 return writer.toString();
   }
   
}
